'use client';

import React, { useState, useEffect } from 'react';
import { Activity, Cpu, Database, HardDrive, Clock, AlertCircle } from 'lucide-react';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import { api } from '@/lib/api';
import toast from 'react-hot-toast';

export default function MonitoringPage() {
  const [token, setToken] = useState<string>('');
  const [stats, setStats] = useState<any>(null);
  const [systemInfo, setSystemInfo] = useState<any>(null);
  const [dbStats, setDbStats] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  // 从 localStorage 获取 token
  useEffect(() => {
    const storedToken = localStorage.getItem('access_token');
    if (storedToken) {
      setToken(storedToken);
    }
  }, []);

  // 加载性能统计
  const loadStats = async () => {
    if (!token) {
      toast.error('请先登录');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('http://localhost:3301/api/monitoring/stats', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        if (response.status === 403) {
          toast.error('需要管理员权限');
        } else {
          toast.error('获取统计失败');
        }
        return;
      }

      const data = await response.json();
      setStats(data);
      toast.success('性能统计加载成功');
    } catch (error) {
      console.error('加载失败:', error);
      toast.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载系统信息
  const loadSystemInfo = async () => {
    if (!token) {
      toast.error('请先登录');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('http://localhost:3301/api/monitoring/system', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        if (response.status === 403) {
          toast.error('需要管理员权限');
        } else {
          toast.error('获取系统信息失败');
        }
        return;
      }

      const data = await response.json();
      setSystemInfo(data);
      toast.success('系统信息加载成功');
    } catch (error) {
      console.error('加载失败:', error);
      toast.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载数据库统计
  const loadDbStats = async () => {
    if (!token) {
      toast.error('请先登录');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch('http://localhost:3301/api/monitoring/database', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        if (response.status === 403) {
          toast.error('需要管理员权限');
        } else {
          toast.error('获取数据库统计失败');
        }
        return;
      }

      const data = await response.json();
      setDbStats(data);
      toast.success('数据库统计加载成功');
    } catch (error) {
      console.error('加载失败:', error);
      toast.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载所有数据
  const loadAll = async () => {
    await loadStats();
    await loadSystemInfo();
    await loadDbStats();
  };

  // 复制 Token
  const copyToken = () => {
    navigator.clipboard.writeText(token);
    toast.success('Token 已复制到剪贴板');
  };

  return (
    <div className="min-h-screen p-8">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 标题 */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent mb-2">
            系统监控
          </h1>
          <p className="text-gray-400">查看系统性能、资源使用和数据统计</p>
        </div>

        {/* Token 显示 */}
        <GlassCard className="p-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-semibold text-white">您的 Token</h2>
              <GlassButton onClick={copyToken} disabled={!token}>
                复制 Token
              </GlassButton>
            </div>
            
            {token ? (
              <div className="space-y-2">
                <div className="p-4 bg-black/30 rounded-lg">
                  <p className="text-sm text-gray-300 break-all font-mono">
                    {token}
                  </p>
                </div>
                <p className="text-sm text-gray-400">
                  ✅ 已自动从登录信息获取 Token
                </p>
              </div>
            ) : (
              <div className="p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
                <p className="text-yellow-300 flex items-center gap-2">
                  <AlertCircle className="w-5 h-5" />
                  请先登录以获取 Token
                </p>
              </div>
            )}
          </div>
        </GlassCard>

        {/* 操作按钮 */}
        <div className="flex gap-4 justify-center">
          <GlassButton onClick={() => { loadStats(); loadSystemInfo(); }} disabled={loading || !token}>
            <Activity className="w-5 h-5 mr-2" />
            加载监控数据
          </GlassButton>
          <GlassButton onClick={loadStats} disabled={loading || !token} variant="secondary">
            性能统计
          </GlassButton>
          <GlassButton onClick={loadSystemInfo} disabled={loading || !token} variant="secondary">
            系统信息
          </GlassButton>
          {/* 数据库统计暂时禁用 - 有技术问题需要修复 */}
          {/* <GlassButton onClick={loadDbStats} disabled={loading || !token} variant="secondary">
            数据库统计
          </GlassButton> */}
        </div>

        {/* 性能统计 */}
        {stats && (
          <GlassCard className="p-6">
            <h2 className="text-xl font-semibold text-white mb-4 flex items-center gap-2">
              <Activity className="w-6 h-6 text-blue-400" />
              性能统计
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">总请求数</p>
                <p className="text-2xl font-bold text-white">{stats.total_requests}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">平均响应时间</p>
                <p className="text-2xl font-bold text-green-400">
                  {stats.avg_response_time?.toFixed(3)}s
                </p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">最大响应时间</p>
                <p className="text-2xl font-bold text-orange-400">
                  {stats.max_response_time?.toFixed(3)}s
                </p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">最小响应时间</p>
                <p className="text-2xl font-bold text-blue-400">
                  {stats.min_response_time?.toFixed(3)}s
                </p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">慢请求数 (&gt;1s)</p>
                <p className="text-2xl font-bold text-yellow-400">{stats.slow_requests}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">错误请求数</p>
                <p className="text-2xl font-bold text-red-400">{stats.error_requests}</p>
              </div>
            </div>
            <div className="mt-4 p-4 bg-white/5 rounded-lg">
              <p className="text-gray-400 text-sm mb-1">运行时间</p>
              <p className="text-xl font-bold text-white">
                {(stats.uptime / 3600).toFixed(2)} 小时
              </p>
            </div>
          </GlassCard>
        )}

        {/* 系统信息 */}
        {systemInfo && (
          <GlassCard className="p-6">
            <h2 className="text-xl font-semibold text-white mb-4 flex items-center gap-2">
              <Cpu className="w-6 h-6 text-green-400" />
              系统资源
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* CPU */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">CPU 使用率</span>
                  <span className="text-white font-bold">{systemInfo.cpu_percent}%</span>
                </div>
                <div className="w-full bg-gray-700 rounded-full h-3 overflow-hidden">
                  <div
                    className="bg-gradient-to-r from-blue-500 to-purple-500 h-full transition-all"
                    style={{ width: `${systemInfo.cpu_percent}%` }}
                  />
                </div>
              </div>

              {/* 内存 */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">内存使用率</span>
                  <span className="text-white font-bold">
                    {systemInfo.memory_used}GB / {systemInfo.memory_total}GB
                    ({systemInfo.memory_percent}%)
                  </span>
                </div>
                <div className="w-full bg-gray-700 rounded-full h-3 overflow-hidden">
                  <div
                    className="bg-gradient-to-r from-green-500 to-teal-500 h-full transition-all"
                    style={{ width: `${systemInfo.memory_percent}%` }}
                  />
                </div>
              </div>

              {/* 磁盘 */}
              <div className="space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-gray-300">磁盘使用率</span>
                  <span className="text-white font-bold">
                    {systemInfo.disk_used}GB / {systemInfo.disk_total}GB
                    ({systemInfo.disk_percent}%)
                  </span>
                </div>
                <div className="w-full bg-gray-700 rounded-full h-3 overflow-hidden">
                  <div
                    className="bg-gradient-to-r from-orange-500 to-red-500 h-full transition-all"
                    style={{ width: `${systemInfo.disk_percent}%` }}
                  />
                </div>
              </div>

              {/* 进程 ID */}
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">进程 ID</p>
                <p className="text-xl font-bold text-white">{systemInfo.process_id}</p>
              </div>
            </div>
          </GlassCard>
        )}

        {/* 数据库统计 */}
        {dbStats && (
          <GlassCard className="p-6">
            <h2 className="text-xl font-semibold text-white mb-4 flex items-center gap-2">
              <Database className="w-6 h-6 text-purple-400" />
              数据库统计
            </h2>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">用户数</p>
                <p className="text-2xl font-bold text-white">{dbStats.users}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">文档数</p>
                <p className="text-2xl font-bold text-white">{dbStats.documents}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">笔记数</p>
                <p className="text-2xl font-bold text-white">{dbStats.notes}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">知识库数</p>
                <p className="text-2xl font-bold text-white">{dbStats.knowledge_bases}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">分类数</p>
                <p className="text-2xl font-bold text-white">{dbStats.categories}</p>
              </div>
              <div className="p-4 bg-white/5 rounded-lg">
                <p className="text-gray-400 text-sm mb-1">聊天会话数</p>
                <p className="text-2xl font-bold text-white">{dbStats.chat_sessions}</p>
              </div>
            </div>
          </GlassCard>
        )}

        {/* 使用说明 */}
        <GlassCard className="p-6 bg-blue-500/10 border-blue-500/30">
          <h3 className="text-lg font-semibold text-blue-300 mb-3">💡 使用说明</h3>
          <div className="space-y-2 text-sm text-gray-300">
            <p>1. 确保你已用<strong className="text-white">管理员账号</strong>登录（admin）</p>
            <p>2. Token 会自动从登录信息中获取</p>
            <p>3. 点击"加载所有数据"按钮查看系统监控信息</p>
            <p>4. 如果提示"需要管理员权限"，请确认你使用的是管理员账号</p>
            <p className="pt-2 border-t border-white/10">
              <strong className="text-yellow-300">注意：</strong>
              只有管理员账号才能访问这些监控信息
            </p>
          </div>
        </GlassCard>
      </div>
    </div>
  );
}

